<?php
declare(strict_types=1);
//一些日期时间组件
class module_date {

    /** 获取月的第一天和最后一天
     *date('Ym') @param string $date
     * @return array
     */
    public function getStartAndEndOfMonth($date = '') : array
    {
        if(empty($date)) $date = date('Ym');
        //获取月份天数、第一天和最后一天
        $year = substr($date, 0, 4);
        $month = substr($date, 4, 2);
        $day_time = "$year-$month-01";
        // 计算该月份的第一天
        $firstDay = date('Y-m-01', strtotime($day_time));
        // 计算该月份的最后一天
        $lastDay = date('Y-m-t', strtotime($day_time));
        //计算天数
        $days = date('t', strtotime($day_time));
        return ['firstDay' => $firstDay, 'lastDay' => $lastDay, 'days' => $days];
    }

    /** 获取周的第一天和最后一天
     * @param string $date
     * @return array
     */
    public function getStartAndEndOfWeek(string $date = '') : array
    {
        $format = 'Y-m-d';
        if(empty($date)) $date = date('YW');
        //获取月份天数、第一天和最后一天
        $year = substr($date, 0, 4);
        $week = substr($date, 4, 2);
        // 计算指定年份和周的第一天（周一）
        $startTime = strtotime("{$year}W" . str_pad($week, 2, '0', STR_PAD_LEFT));
        $startOfWeek = date($format, $startTime);
        // 计算该周的最后一天（周日）
        $endTime = strtotime("+6 days", $startTime);
        $endOfWeek = date($format, $endTime);
        return ['firstDay' => $startOfWeek, 'lastDay' => $endOfWeek, 'days' => 7];
    }
}